package com.clp.protocol.modbus_tcp.mb_frame.mb_body.mb_data.req;

import com.clp.protocol.core.utils.ByteUtil;
import com.clp.protocol.modbus_tcp.definition.MbByteOrder;
import com.clp.protocol.modbus_tcp.mb_frame.mb_body.mb_data.ReqMbData;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.nio.ByteOrder;
import java.util.Objects;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class PresetSingleRegReqMbData implements ReqMbData {
    /**
     * 设置地址
     */
    private int setAddr;
    /**
     * 设置内容
     */
    private int setVal;

    @Override
    public ReqMbData initBy(ByteBuf buf) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isValid() {
        if (setAddr < 0 || setAddr > 0xFFFF) return false;
        return setVal >= 0 && setVal <= 0xFFFF;
    }

    @Override
    public void writeTo(ByteBuf buf) {
        buf.writeBytes(MbByteOrder.setAddrOrder == ByteOrder.BIG_ENDIAN ?
                ByteUtil.intToBytes2BE(setAddr) : ByteUtil.intToBytes2LE(setAddr));
        buf.writeBytes(MbByteOrder.setRegOrder == ByteOrder.BIG_ENDIAN ?
                ByteUtil.intToBytes2BE(setVal) : ByteUtil.intToBytes2LE(setVal));
    }

    @Override
    public String toString() {
        return "设置地址：" + setAddr + ", 设置内容：" + setVal;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PresetSingleRegReqMbData that = (PresetSingleRegReqMbData) o;
        return setAddr == that.setAddr && setVal == that.setVal;
    }

    @Override
    public int hashCode() {
        return Objects.hash(setAddr, setVal);
    }
}
